<script setup>
import {onMounted, ref} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'

// 引入hotel.js中的API函数
import {
  getHotelRoomsService,
  addHotelRoomService,
  deleteHotelRoomService,
  updateHotelRoomService,
  getAllHotelRoomsService
} from '@/api/hotel.js'
import {Delete, Edit, Search} from "@element-plus/icons-vue";

// 获取路由对象
const route = useRoute();

// 传递的酒店名称
const hotelName = route.query.hotelName || '';

// 显示弹窗
const dialogVisible = ref(false);

// 分页条数据模型
const pageNum = ref(1); // 当前页
const total = ref(20); // 总条数
const pageSize = ref(3); // 每页条数

// 酒店房间列表数据模型
const rooms = ref([
  {
    "roomNumber": 502,
    "hotelName": "string",
    "isBooked":0
  }
]);

// 搜索输入
const input = ref('');
// 选中的数据项
const selectedItems = ref([]);
// 控制抽屉是否显示
const visibleDrawer = ref(false)
// 添加表单数据模型
const roomModel = ref({})

// 重置房间模型
const getDefaultRoomModel = () => ({
  roomNumber: 0,
  hotelName: '',
  isBooked: 0,
  roomType: 0,
});

// 获取房间数据
const getRooms = async () => {
  try {
    if (!hotelName) {
      let result = await getAllHotelRoomsService();
      rooms.value = result.data;
      return;
    }
    // 调用接口
    let result = await getHotelRoomsService(hotelName);
    // 将数据存储，用于渲染视图
    rooms.value = result.data;
    // 更新总条数，用于分页显示
    total.value = result.data.length;
  } catch (error) {
    ElMessage({type: "error", message: "获取列表失败"});
  }
}

// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  // 刷新列表
  getRooms();
}

// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  // 刷新列表
  getRooms();
}

const inputSearch = async () => {
  const keyword = input.value.trim(); // 去除首尾空格
  if (!keyword) {
    await getRooms(); // 如果搜索关键词为空，则显示所有房间列表
    return; // 如果搜索关键词为空，直接返回，不执行后续操作
  }

  const keywordNumber = parseInt(keyword, 10); // 将关键词转换为整数

  if (isNaN(keywordNumber)) {
    ElMessage({ type: "error", message: "请输入有效的房间号" });
    return;
  }

  try {
    // 根据房间号进行搜索
    total.value = rooms.value.filter(room =>
        room.roomNumber === keywordNumber
    ).length;
    rooms.value = rooms.value.filter(room =>
        room.roomNumber === keywordNumber
    );
  } catch (error) {
    console.error('搜索房间时出错：', error);
    ElMessage({ type: "error", message: "搜索房间出错" });
  }

  input.value = ''; // 清空输入框
};

// 添加房间
const addRoom = async () => {
  try {
    // 调用接口
    roomModel.value.hotelName = hotelName;
    roomModel.value.isBooked = 0;
    let result = await addHotelRoomService(hotelName, roomModel.value);
    if (result.code === 0) {
      ElMessage.success(result.message || '添加成功');
    }else {
      ElMessage.error(result.message || '添加失败');
    }

    // 房间模型置空
    roomModel.value = getDefaultRoomModel();
    // 让抽屉消失
    visibleDrawer.value = false;
    // 刷新当前列表
    await getRooms();
  } catch (error) {
    console.error('添加房间时出错：', error);
    ElMessage.error('添加房间时出错，请重试');
    // 让抽屉消失
    visibleDrawer.value = false;
  }
}

// 取消添加房间
const cancel = async () => {
  // 房间数据模型置空
  roomModel.value = getDefaultRoomModel();
  // 让抽屉消失
  visibleDrawer.value = false;
}

// 批量删除
// 处理选中事件
const handleSelectionChange = (selected) => {
  selectedItems.value = selected;
};

// 删除选中项
const deleteSelectedRooms = () => {
  if (!Array.isArray(selectedItems.value) || selectedItems.value.length === 0) {
    ElMessage({type: "info", message: "请先选择要删除的项"});
    return;
  }
  ElMessageBox.confirm("确认删除选中的项吗?", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(async () => {
        // 调用后端删除数据的函数
        for (const item of selectedItems.value) {
          await deleteHotelRoomService(hotelName, item.roomNumber);
        }
        // 清空选中项
        selectedItems.value = [];
        // 刷新列表
        await getRooms();
        ElMessage({type: "success", message: "删除成功"});
      })
      .catch(() => {
        ElMessage({type: "info", message: "删除已取消"});
      });
};

// 删除单个房间
const deleteRoom = (row) => {
  ElMessageBox.confirm("确认删除该房间吗?", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "我再想想",
    type: "warning",
  }).then(async () => {
    // 调用接口
    let result = await deleteHotelRoomService(hotelName, row.roomNumber);
    if (result.code === 0) {
      ElMessage.success(result.message || '删除成功');
    } else {
      ElMessage.error(result.message || '删除失败');
    }

    await getRooms();
  }).catch(() => {
    ElMessage({type: "info", message: "删除已取消"});
  })
};

// 修改房间信息
// 显示
const handleOpen = async (row) => {
  dialogVisible.value = true
  // 获取编辑房间
  roomModel.value = row;
}

const editRoom = async () => {
  // 编辑房间
  try {
    roomModel.value.hotelName = hotelName;
    // 调用接口
    let result = await updateHotelRoomService(hotelName, roomModel.value.roomNumber, roomModel.value);
    if (result.code === 0 ) {
      ElMessage.success(result.message || '修改成功');
    } else {
      ElMessage.error(result.code || '修改失败');
    }
    dialogVisible.value = false;
  } catch (error) {
    console.error('编辑房间时出错：', error);
    ElMessage.error('编辑房间时出错，请重试');
  }
}

// 弹窗关闭
const handleClose = () => {
  // 房间模型置空
  roomModel.value = getDefaultRoomModel();
  // 弹窗关闭
  dialogVisible.value = false;
}

onMounted(() => {
  getRooms();
})
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>{{ hotelName }}酒店房间管理</span>
        <div class="extra">
          <el-button type="primary" @click="visibleDrawer = true">添加房间</el-button>
        </div>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item >
        <el-input v-model="input" style="width: 240px" placeholder="请输入房间号" clearabl :prefix-icon="Search"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="inputSearch">搜索</el-button>
        <el-button @click="deleteSelectedRooms">批量删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 房间列表 -->
    <el-table
        ref="multipleTableRef"
        :data="rooms.slice((pageNum - 1) * pageSize, pageNum * pageSize)"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="房间号" width="100" prop="roomNumber"></el-table-column>
      <el-table-column label="酒店名称" prop="hotelName"></el-table-column>
      <el-table-column label="预定状态" prop="isBooked"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Delete" circle plain type="danger" @click="deleteRoom(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10, 15]"
        layout="jumper, total, sizes, prev, pager, next"
        background :total="total" @size-change="onSizeChange"
        @current-change="onCurrentChange" style="margin-top: 20px;
        justify-content: flex-end" />

    <!-- 抽屉 -->
    <el-drawer
        title="添加房间"
        v-model="visibleDrawer"
        width="300px"
        direction="rtl"
    >
      <el-form ref="roomFormRef" :model="roomModel" label-width="80px">
        <el-form-item label="房间号">
          <el-input v-model="roomModel.roomNumber"></el-input>
        </el-form-item>
        <el-form-item label="酒店名称">
          <el-input v-model="hotelName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="addRoom">提交</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" title="编辑房间" width="30%">
      <el-form-item label="房间号">
        <el-input v-model="roomModel.roomNumber"></el-input>
      </el-form-item>
      <el-form-item label="酒店名称">
        <el-input v-model="hotelName"></el-input>
      </el-form-item>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="editRoom">提交</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped>
.page-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.extra {
  display: flex;
  align-items: center;
}

.el-table__fixed-header-wrapper {
  margin-top: 0;
}

.el-table__fixed-header-wrapper table {
  margin-top: 0;
}

.el-table__fixed-header-wrapper table th {
  background-color: #f5f5f5;
}

.el-table__fixed-header-wrapper table th:first-child {
  width: 55px;
}

.el-table__fixed-header-wrapper table th:nth-child(2) {
  width: 100px;
}

.el-table__fixed-header-wrapper table th:nth-child(3) {
  width: 100px;
}
</style>